#coding:utf8
'''
Created on 2013-9-22
玩家类
@author: jt
'''
from app.mem.mPlayer import player_m,playerPet_m, playerFight_m,\
    playerInstance_m
from app.scense.core.pet.pet import Pet
from app.db import player_petdb, player_fightdb
from app.scense.component.welfare.welfare import Welfare
from app.js import Obj
from app.scense import tables

class Player(object):
    '''玩家'''

    def __init__(self,pid,did=-1):
        '''初始化玩家类'''
        self.id=pid #玩家id
        self.instancedid=0 #副本动态id
        self.did=did #玩家登陆动态id
        pl_mode=player_m.getObj(pid)
        info = pl_mode.get("data")
        self.uname=info.get('uname') #账号
        self.name=info.get('nickname')
        self.gold=info.get('gold')#金币
        self.silvermoney=info.get('silvermoney') #银币
        self.luck = info.get('luck')#角色宠物强化幸运值
        self.createtime=info.get('createtime')  #角色创建时间
        self.pets={} #角色解锁和未解锁的宠物列表     key:角色宠物id,value:宠物实例  存储于player_pet表
        self.fightPets={1:0,2:0,3:0,4:0} #出战的宠物      角色宠物id          存储于player_fight表
        self.fightcount=4 #最多出战数量
        self.ciid=0       #已通关副本id
        self.welfare = Welfare(self)#福利
        self.initdata()
        
    
    def assessment(self,typeid,val):
        '''触发任务
        @param typeid: int 任务类型
        @param val: int 可以使通关的id,也可以是充值的数量，也可以是消费金币的数量 
        '''
        self.welfare.assessment(typeid, val)
        
    def updateCiid(self,ciid):
        '''修改已经通关的副本id
        @param ciid: int 已通关副本id
        '''
        self.ciid=ciid
        pi=playerInstance_m.getObj(self.id)
        if not pi:
            data={"pid":self.id,"instanceid":ciid}
            newpi=playerInstance_m.new(data)
            newpi.syncDB()
        else:
            pi.update("instanceid", ciid)            
            pi=playerInstance_m.getObj(self.id)
            info = pi.get("data")
            self.ciid=info.get("instanceid",0)
            
        from app.scense.tables import petNewInstance_table
        npetinfo=petNewInstance_table.get(ciid,None)
        if npetinfo:  #如果通关这个副本之后能够增加新的可解锁宠物
            flg=False
            for petobj in self.pets.values():
                if petobj.petid==npetinfo['petid']:
                    flg=True
            if not flg: #如果角色没有这个类型的宠物
                petid=npetinfo['petid']   #新的宠物id 
                silver=npetinfo['silver'] #解锁需要的银币数量
                self.addPet(petid,silver)
            
#            if not player_petdb.selectBypidAndpetid(self.id, npetinfo['petid']):#如果角色没有这个宠物: 
#                petid=npetinfo['petid']   #新的宠物id 
#                silver=npetinfo['silver'] #解锁需要的银币数量
#                self.addPet(petid,silver)
            
        
    
    def initdata(self):
        '''初始化'''
        ppdata=player_petdb.getByPid(self.id) #角色解锁和未解锁的宠物
        if ppdata:
            for item in ppdata:
                pet=Pet(item['id'])
                self.pets[item['id']]=pet
        pi=playerInstance_m.getObj(self.id)
        if pi:
            info = pi.get("data")
        else:
            info = {}
        self.ciid=info.get("instanceid",0)
        fightlist=player_fightdb.getListByPid(self.id)#战斗队列的宠物
        if fightlist:
            self.fightPets=fightlist
    
    def addFightPet(self,ppid,postion,rsp):
        '''添加一个宠物到战斗列表中
        @param ppid: int 角色宠物id
        @param postion: int 位置
        '''
        postion=postion-1
        if ppid in self.fightPets.values():
            return False  #这个宠物已经存在于备战区
        
        if postion>4 or postion<0:
            return False  #位置传错了
        
        self.fightPets[postion]=ppid
        
        info=playerFight_m.getObj(self.id)
        if not info:
            data={"pid":self.id,"fightpet":str(self.fightPets)}
            pf=playerFight_m.new(data)
            pf.syncDB()
        else:
            info.update("fightpet", str(self.fightPets))
        
        
    def moveHalt(self,ppid,postion,rsp):
        '''把宠物从备战区移动到休息区
        @param ppid: int 角色宠物id
        @param postion: int 备战区位置
        @param rsp: obj 返回的信息
        '''
        ppid=self.fightPets.get(postion,-1)
        if not self.pets.has_key(ppid):
            rsp.result=False
            return
        info=playerFight_m.getObj(self.id)
        info.update('fightpet', str(self.fightPets))
    
        
    def addPet(self,petid,silver,level=1,exp=1,unlocks=0):
        '''添加一个宠物
        @param templateid: int 宠物模板id,pet表主键id
        '''
        data={'pid':self.id,'petid':petid,'level':1,'exp':1,'unlocks':0,'silver':silver,'newgid':0,'qhhplv':0,'qhattlv':0}
        pobj=playerPet_m.new(data)
        pobj.syncDB()
        ppid=pobj.get("id")
        if not ppid:
            return False
        self.pets[ppid]=Pet(ppid)
        return True
    
    
    def getFightPetsInfo(self,rsp):
        '''获取备战区宠物详细信息 最多4个'''
        for key,ppid in self.fightPets.items():
            if ppid>0:
                pfinfo=Obj()
                pfinfo.option=key    #第几个位置
                pfinfo.petinfo=Obj() #宠物信息
                objp= self.pets.get(ppid)#宠物实例
                pfinfo.btype=objp.btype
                objp.getAllPetInfo(pfinfo.petinfo)
                rsp.pfinfo.append(pfinfo)

        
        
    
    def getAllPetInfo(self,rsp):
        '''获取所有角色所有宠物信息列表'''
        fn=0 #战斗列表中所有宠物的战斗力之和
        if len(self.pets)<1:
            rsp.result=False
            rsp.message=u'没有宠物'
        else:
            for ppid in self.pets:
                pinfo=Obj()
                pet=Pet(ppid)
                fn+=pet.fn
                pet.getShowPetInfo(pinfo)
                rsp.psinfo.append(pinfo)
            rsp.result=True
            rsp.fightv=fn
            
    def countFn(self):
        '''计算当前小队战力
        '''
        fn = 0
        for pid in self.fightPets.values():
            if pid > 0:
                pet=self.pets[pid]
                fn += pet.fn
        return fn
    
#     def getAllUnlockPets(self):
#         '''获取所有已解锁宠物
#         '''
#         unlockPets = {}
#         for i in self.pets.items():
#             if i[1].flg:
#                 unlockPets[i[0]] = i[1]
#         return unlockPets
    
    def getAllPetQhInfo(self,info):
        '''获取所有小伙伴强化信息
        '''
        from app.scense.tables import intensify_table
        info.teaminfo = []
        for pet in self.pets.values():
            if pet.flg:
                petInfo = Obj()
                petInfo.name = pet.name
                petInfo.ppid=pet.ppid
                petInfo.level = pet.qhhplv + pet.qhattlv
                petInfo.levellimit = pet.qhlimit
                petInfo.resource = pet.resourceid
                petInfo.headid = pet.headid
                petInfo.color = pet.color
                petInfo.hp = pet.countAllAtt(1)
                petInfo.hpmoney = intensify_table.get(pet.qhhplv+1,{'money':0})['money']
                petInfo.att = pet.countAllAtt(2)
                petInfo.attmoney = intensify_table.get(pet.qhattlv+1,{'money':0})['money']
                petInfo.status = pet.upmoney
                info.teaminfo.append(petInfo)
        
    def getIntensifyInfo(self,response):
        '''获取强化界面信息
        '''
        response.data = []
        info = Obj()
        info.fighting = self.countFn()
        info.silvermoney = self.silvermoney
        info.luck = self.luck
        self.getAllPetQhInfo(info)
        response.data.append(info)
    
    def setDid(self,did):
        '''更改玩家登陆动态id'''
        self.did=did
        
    def closes(self):
        '''玩家退出前的操作'''
        obj=player_m.getObj(self.id)
        obj.syncDB()
    
    def addGold(self,count):
        '''增加金币数量'''
        self.gold+=count
        self.updatePlayerTable("gold", self.gold)
        
    def addSilver(self,count):
        '''增加银币数量'''
        self.silvermoney+=count
        self.updatePlayerTable("silvermoney", self.silvermoney)
        
    def delSilver(self,count):
        '''减少银币数量'''
        if self.silvermoney<count:
            return False
        self.silvermoney-=count
        self.updatePlayerTable("silvermoney", self.silvermoney)
        return True
    
    def addPetsExp(self,exp):
        '''给出战宠物增加经验
        @param exp: int 要增加的经验值
        '''
        for pid in self.fightPets.values():
            if pid > 0:
                pet=self.pets.get(pid)
#                pet = Pet(pid)
                pet.addExp(exp)
    def updatePlayerTable(self,key,value):
        '''更改角色表数据'''
        obj=player_m.getObj(self.id)
        obj.update(key, value)
